package slap.mvc.result;

import java.util.Map;

import jodd.io.StreamUtil;

import slap.exception.UnexpectedException;
import slap.http.Request;
import slap.http.Response;
import slap.template.Template;
import slap.util.GZIP;
import slap.util.MimeTypes;

/**
 * 200 OK with a template rendering
 */
public class RenderTemplate extends Result {

    private String templateName;
    private Map<String, Object> models;

    public RenderTemplate(String templateName, Map<String, Object> models) {
    	this.templateName = templateName;
    	this.models = models;
    }

    public void apply(Request request, Response response) {
        try {
        	byte[] b = Template.render(templateName, models).toString().getBytes();
        	if(request.acceptGzip()){
        		response.enableGZipTransfer();
        		response.out.write(GZIP.compress(b));
        	}else{
        		response.out.write(b);
        	}
        	setContentTypeIfNotSet(response, "charset:utf-8;text/html");
        } catch (Exception e) {
            throw new UnexpectedException(e);
        }
    }

}
